// SlagCar/OrderAdd/components/selectDriver/selectDriver.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    activeDriver: {
      type: Array,
      observer(val){
        this.setData({activeId: val})
      }
    },
    show: {
      type: Boolean,
      value: false,
      observer(val){
        if (val && !this.data.isLoaded) {
          this.setDriverLevel(1)
          this.data.isLoaded = true
        }
        if (val){
          this.initObserver()
        } else {
          this.data.lazyLoadOb.disconnect();
        }
      }
    }

  },

  /**
   * 组件的初始数据
   */
  data: {
    // 车队
    level1: [
      {id: 'all',text: '全部',children: []},
    ],
    levelKey1: 0,
    // 分队
    level2: [
      {id: 'all',text: '全部',children: []},
    ],
    levelKey2: 0,
    // 司机
    level3: [],
    // 已选司机
    activeId: [],

    // 顶部导航
    tabActive: 0,

    // 分组加载
    groupList: [],
    // 分组加载索引
    lazyLoadIdx: 0,
    // 分组数据
    driverList: [],

  //  搜索
    searchValue: ''

  },

  /**
   * 组件的方法列表
   */
  methods: {

    //获取司机分级信息
    getDriverLevel(post){
      let url = 'ZTAuth/query_driver_inf_lv';
      return new Promise(resolve => {
        wx.showLoading({mask: true})
        wx.$post(5,url,post).then(res => {
          if (res.errcode != 0) return;
          wx.hideLoading()
          let data = res.data.row || [],
            arr = [],
            id = '',text = '',
            idName = '',textName = '';
          if (post.lv === 1){
            idName = 'r_suoshuchedui';textName = 'r_suoshuchedui_value';
            arr.push({
              text: '全部',
              id: 'all',
              children: []
            })
          }
          if (post.lv === 2){
            idName = 'suoshufendui';textName = 'suoshufendui_value';
            arr.push({
              text: '全部',
              id: 'all',
              children: []
            })
          }
          if (post.lv === 3){
            idName = 'row_id';textName = ['chelianghaoma','jiashiyuanxingming','suoshufendui_value'];
          }
          data.forEach(item => {
            let id = item[idName],
              {r_suoshuchedui,suoshufendui} = item
            if (!id) return;
            let text = '';
            if (typeof textName === 'object'){
              text = [];
              textName.forEach(ite => {
                if (ite === 'suoshufendui_value' && !item[ite]) {
                  item.r_suoshuchedui_value && text.push(item.r_suoshuchedui_value)
                }else {
                  item[ite] && text.push(item[ite])
                }
              });
              text = text.join('-');
            }else {
              text = item[textName] || '';
            }
            arr.push({
              text,
              id,
              r_suoshuchedui,suoshufendui
            })
          });
          resolve(arr)
        })
      })
    },

    //设置显示车队、分队、司机
    setDriverLevel(lv){
      let {level1,levelKey1,level2,levelKey2} = this.data;
      //车队
      if (lv === 1){
        this.getDriverLevel({lv: 1}).then(res =>{
          this.setData({level1: res,levelKey1: 0})
          this.setDriverLevel(2)
        })
        return
      }
      let item1 = level1[levelKey1] //一级车队
      //分队
      if (lv === 2){
        // 已有
        if (item1.children &&item1.children.length){
          this.setData({
            level2: item1.children,
            levelKey2: 0
          });
          this.setDriverLevel(3)
          return
        }
        let post = {lv: 2};
        post.lv_1_row_id = item1.id === 'all' ? '' : item1.id;
        this.getDriverLevel(post).then(res => {
          this.setData({
            // [`level1[${levelKey1}].children`]: res,
            level2: res,
            levelKey2: 0
          });

          this.data.level1[levelKey1].children = res
          this.setDriverLevel(3)
        })
        return
      }
      let item2 = level2[levelKey2];
      //司机
      if (lv === 3){
        if (item2.children && item2.children.length){
          this.setData({
            // level3: item2.children,
            tabActive: 0
          })
          this.data.level3 = item2.children
          this.formatDriverList(item2.children)
          return
        }
        let post = {lv: 3};
        post.lv_1_row_id = item1.id === 'all' ? '' : item1.id;
        post.lv_2_row_id = item2.id === 'all' ? '' : item2.id;
        this.getDriverLevel(post).then(res => {
          this.setData({
            // [`level2[${levelKey2}].children`]: res,
            // level3: res,
            tabActive: 0
          });
          this.data.level2[levelKey2].children = res
          this.data.level3 = res
          this.formatDriverList(res)
        })
      }
    },
    // 显示已勾选司机
    setDriverSelected(){
      let {level2,levelKey2,activeId} = this.data;
      let item2 = level2[levelKey2],
        level3 = item2.children;
      level3 = level3.filter(item =>{
        return activeId.includes(item.id)
      });
      this.formatDriverList(level3)
      // this.setData({level3})
    },
    // 侧边导航栏切换
    onSidebarChange1(e){
      this.setData({levelKey1: e.detail})
      this.setDriverLevel(2)
    },
    onSidebarChange2(e){
      this.setData({levelKey2: e.detail})
      this.setDriverLevel(3)
    },

    // 司机顶部标签切换
    onTabsChange(event) {
      let {index} = event.detail;
      this.setData({tabActive: index})
      if (!index) this.setDriverLevel(3)
      else {
        this.setDriverSelected();
      }
    },

    // 点击选择司机
    onClickItem(e){
      const { activeId, } = this.data;
      let {id} = e.currentTarget.dataset;

      const index = activeId.indexOf(id);
      if (index > -1) {
        activeId.splice(index, 1);
        // this.setBadge(-1)
      } else {
        activeId.push(id);
        // this.setBadge(1)
      }

      this.setData({ activeId });
    },
    //全选司机
    checkAllDriver({detail}){
      let {level2,levelKey2,activeId} = this.data;
      let item2 = level2[levelKey2],
        level3 = item2.children,
        num = 0 // 已选司机数量
      level3.forEach(item =>{
        let index = activeId.indexOf(item.id);
        if (detail && index < 0) {
          activeId.push(item.id);
          num++
        }
        if (!detail && index >= 0) {
          activeId.splice(index, 1);
          num--
        }
      })
      this.setData({checkAll: detail,activeId});
      // this.setBadge(num)
    },
    // 未完善
    setBadge(num){
      let {level1,levelKey1,level2,levelKey2} = this.data,
        item1 = level1[levelKey1],
        item2 = level2[levelKey2];
      let badge1 = Number(item1.badge || 0) + num,
        badge2 = Number(item2.badge || 0) + num;
      this.setData({
        [`level1[${levelKey1}].badge`]: badge1,
        [`level2[${levelKey2}].badge`]: badge2,
      })
    },

    // 格式化司机数据，改为二维数组，每组20条数据，分页加载
    formatDriverList(arr){
      let n = 20;
      let driverList = Array.from({ length: Math.ceil(arr.length / n) }, (_, i) =>
        arr.slice(i * n, i * n + n)
      );
      this.data.driverList = driverList;
      this.setData({groupList: [driverList[0]],lazyLoadIdx: 1});

    },
    // 加载下一页
    lazyLoadNext(){
      let {lazyLoadIdx,groupList,driverList} = this.data;
      if (lazyLoadIdx >= driverList.length) return;
      this.setData({
        [`groupList[${lazyLoadIdx}]`]: driverList[lazyLoadIdx],
        lazyLoadIdx: lazyLoadIdx +1
      })
    },
    // 初始化监听
    initObserver(){
      this.data.lazyLoadOb = this.createIntersectionObserver();
      this.data.lazyLoadOb.relativeTo('#viewport',{bottom: 50}).observe('#observer',res =>{
        console.log('res.intersectionRatio',res.intersectionRatio)
        if (res.intersectionRatio) this.lazyLoadNext();
      });
    },
    confirmDriver(){
      this.triggerEvent('confirm', this.data.activeId)
    },
    onCancel(){
      this.triggerEvent('cancel',)

    },


    //搜索输入框变化
    searchChange(e){
      let {type} = e.currentTarget.dataset,
        {searchValue} = this.data;
      searchValue = e.detail;
      this.setData({searchValue});
    },
    // 搜索
    bindSearch(e){
      let {searchValue,level2,levelKey2} = this.data;
      let item2 = level2[levelKey2],
        level3 = item2.children;
      level3 = level3.filter(item =>{
        return item.text.indexOf(searchValue) >= 0
      });

      this.formatDriverList(level3)
    },
  },

  ready(){
  }
})
